/**
 * Created by Administrator on 2015/11/2.
 */
$(function(){
    var woodBox = $(".wood-box"); //盒子
    var woods = $(".wood"); //所有木头
    var wood1 = $(".wood-origin"); //第一根木头
    var moveWood = $(".moveWood"); //移动的木头
    var woodNum = 1; //木头总数
    var nowLeft; //新木头实时位置
    var initLeft = -250; //木头初始位置
    var woodWidth = 200; //木头宽度200px
    var woodHeight = 20; //木头高度30px
    var speed = 10; //速度
    var step = 1; //步数
    var gameTimer; //计时器
    var flag = true; //成功失败标志
    var score = $('.score'); //得分
    // 界面初始化
    init();
    function init(){
        wood1.css({
            'left':(woodBox.width()-wood1.width())/2+"px",
            'height': woodHeight+"px"
        });
    }
    function rebuild(newW) {
        if(woodNum%5==0){
            step++;
        }
        nowLeft=initLeft;
        moveWood.css({
            'bottom': (woodNum*woodHeight) + 'px',
            'width': newW + 'px'
        });
        gameTimer=setInterval(woodMove,speed);
    };
    function woodMove() {
        if(nowLeft>600){ nowLeft=initLeft }else{ nowLeft=nowLeft+step };
        moveWood.css({
            'left': nowLeft + 'px',
            'bottom': (woodNum*woodHeight) + 'px'
        });
    };
    $('#btnCatch').on('click',function(){
        woodNum = $(".wood").length+1;
        var lastWood = $(".wood:last"); //最后顶上的一根木头
        var lastWoodW = lastWood.width();
        var lastWoodL = lastWood.position().left; //jquery获取相对于它最近的具有相对位置(position:relative)的父级元素的距离
        console.log(lastWoodL);
        //新木头
        var nowWoodB = $(".wood").length*woodHeight;
        var nowWoodL;
        var nowWoodW;
        var a1,a2,b1,b2;
        a1 = nowLeft; //移动木头左位置
        a2 = nowLeft + lastWoodW; //移动木头右位置
        b1 = lastWoodL; //顶部木头左位置
        b2 = lastWoodL + lastWoodW; //顶部木头右位置
        if(a1 <= b1 && a1 < b2 && a2 > b1){
            nowWoodW = a2 - b1;
            nowWoodL = lastWoodL;
        }else if(a1 >= b1 && a1 < b2 && a2 > b2){
            nowWoodW = b2 - a1;
            nowWoodL = nowLeft;
        }else{
            flag = false;
        }
        if(flag == true){
            //生成新木头html元素
            var newWood = "<div class='wood' style='bottom:"+ nowWoodB +"px; width:"+ nowWoodW +"px; left:"+ nowWoodL +"px'></div>";
            woodBox.append(newWood);
            clearInterval(gameTimer);
            if(nowWoodB>=(woodBox.height()-woodHeight)){
                gameOver("success");
                moveWood.remove();
            }else{
                rebuild(nowWoodW);
            }
            score.html(woodNum-1);
        }else{
            gameOver("failed");
        }
    });
    //结果
    function gameOver(result){
        if(result=="success"){alert("成功过河!")}else{alert("失败! 搭了"+(woodNum-1)+"根木头")}
        clearInterval(gameTimer);
    }
    rebuild(woodWidth);
});